<template>
	<div id="mailList">
		<div class="i_maxW">
			<div class="u_crumbs">
				<router-link to="/personal/index" class="fade-router" exact>个人中心</router-link>
				<strong><i>></i>我的资源</strong>
			</div>
			<!--  -->
			<div class="u_resource">
				<div class="u_resourceH clear">
					<div class="u_resourceH_l fl">
						<router-link to="/personal/resource/add" class="fade-router">上传</router-link>
						<el-button type="primary" @click="getchart()" v-show="resourceList.length > 0">统计</el-button>
						<template>
							<el-select filterable v-model="subjectId" placeholder="请选择" @change="changeSelect()">
								<el-option v-for="item in subjectList" :key="item.id" :label="item.name" :value="item.id">
								</el-option>
							</el-select>
						</template>
					</div>
					<!--  -->
					<div class="u_resourceH_r fr">
						<el-input size="medium" placeholder="资源名称" suffix-icon="el-icon-search" v-model.trim="resourceName" @change="changeInputName">
						</el-input>
					</div>
				</div>
				<!--  -->
				<ul>
					<li class="resourceLs clear" v-for="(item, index) in resourceList" :key="item.id">
						<div class="resource_icon fl">
							<img :src='`${BASE_URL}/images/format/resourceicon8.png`' v-if="item.file_type == 0">
							<img v-else :src='`${BASE_URL}/images/format/resourceicon${item.file_type}.png`'>
						</div>
						<div class="resource_txt">
							<div class="resource_link clear">
								<a @click="pathURL(item.id)">
									{{ item.name }}.{{item.postfix}}
								</a>
								<div class="resource_ioperation fr">
									<el-popover placement="bottom" width="" popper-class="ioperation_hover" trigger="hover">
										<ul class="r_ioperation">
											<li @click="whetherOpen(item.id, 'off')" v-if="item.authority == 0">设为公开</li>
											<li @click="whetherOpen(item.id, 'no')" v-if="item.authority != 0">设为私有</li>
											<li>
												<router-link v-if="item.file_type === 2" :to="{path:'/personal/journal/edit',query:{id: item.id}}" class="fade-router">编辑</router-link>
												<router-link v-else :to="{path:'/personal/resource/edit',query:{id: item.id}}" class="fade-router">编辑</router-link>
											</li>
											<li @click="removeList(item.id)">删除</li>
										</ul>
										<i slot="reference" class="el-icon-arrow-down"></i>
									</el-popover>
								</div>
							</div>
							<!--  -->
							<div class="resource_info resource_state">
								<template>
									<button class="r_state1" type="text" v-if="item.authority == 1 && item.status == 1">公开</button>
									<button class="r_state2" type="text" v-if="item.authority == 0">不公开</button>
								</template>
								<template v-if="roleBaseid(4, 5)">
									<button class="a_state3" type="text" v-if="item.authority ==1 && item.status == 3">拒绝</button>
									<button class="a_state2" type="text" v-if="item.authority ==1 && item.status == 2">审核中</button>
									<button class="a_state1" type="text" v-if="item.authority ==1 && item.status == 1">已通过</button>
								</template>
								<span>学科： {{ item.cs_name }}</span>
								<span>大小： {{ ByteSwitch(item.filesize) }}</span>
								<span>收藏：{{ item.favs }}</span>
								<span>{{item.frendly_time}}</span>
							</div>
						</div>
					</li>
				</ul>
				<div class="dependent" v-if="resourceList.length == 0">
					<i class="ipm image_nofound"></i>
					<p>
						还没发现任何相关的内容哦~
					</p>
				</div>
				<!--  -->
				<div class="pageBox" v-if="total_number > page_size">
					<el-pagination @current-change="change_page" :current-page="page_index" :page-size="page_size" layout="prev, pager, next" :total="total_number">
					</el-pagination>
				</div>
			</div>
		</div>
		<!--  -->
		<transition name="el-fade-in-linear">
			<div class="imasking statisticsBox" :class="{statisticsVisible: isActive}">
				<div class="imak_bg">
					<div class="imak_h">
						<span>资源统计</span>
						<i class="el-icon-close" @click="isActive = false"></i>
					</div>
					<div class="chart" id="chart">
						<IEcharts :option="polar" />
					</div>
				</div>
			</div>
		</transition>
	</div>
</template>
<script>
import IEcharts from 'vue-echarts-v3/src/lite.js';
import 'echarts/lib/chart/pie';
import 'echarts/lib/component/title';
import 'echarts/lib/component/legend';

export default {
	components: { IEcharts },
	data() {
		return {
			myChart: {},
			subjectId: 0, //学科
			subjectList:  this.$g.subjectList, //学科表
			resourceList: [], //资源列表
			page_index: 1, //分页
			page_size: this.$g.page_size, //分页--当前页
			total_number: 0, //分页总数
			resourceName: '', //资源名称
			isActive: false, //统计图
			total_type: [],
			polar: {
				backgroundColor: '#fff',
				color: ['#85b6b2', '#6d4f8d', '#cd5e7e', '#e38980', '#f29e29', '#f7db88', '#ffdb6d'],

				title: {
					text: '',
					x: 'right',
					left: '50%',
					top: 40,
					textStyle: {
						color: '#6c6c6c',
						fontSize: '14',
					}
				},
				height: { // 图表高度
					type: String,
					default: '250px'
				},
				width: { // 图表宽度
					type: String,
					default: '100%'
				},
				legend: {
					x: 'right',
					left: '50%',
					top: 80,
					icon: 'circle',
					data: [],
					formatter: "",
					textStyle: {
						color: '#6c6c6c',
						fontSize: '12',
						width: "150px"
					}

				},
				series: [{
					name: '',
					type: 'pie',
					radius: '50%',
					"center": ["25%", "40%"],
					avoidLabelOverlap: false,
					itemStyle: {
						normal: {
							label: {
								show: true,
								// formatter: function(param) {
								// 	console.info(param.name  +  ': ' + (param.value/10240).toFixed(3))
								// 	return param.name  +  '\n ' + (param.value/10240).toFixed(3) + '%';
								// },
							},
							labelLine: {
								show: false
							},
							shadowBlur: 40,
							shadowColor: 'rgba(40, 40, 40,0.1)',
						}
					},
					label: {
						normal: {
							show: false,
							position: 'left'
						},
						emphasis: {
							show: true,
							textStyle: {
								fontSize: '14'
							}
						}
					},
					labelLine: {
						normal: {
							show: true,
						}
					},
					data: []
				}]
			},
			//
		};
	},
	created() {
		this.getResourceLs();
	},
	methods: {
		/**
		 * 跳前台查看详情
		 * @DateTime 2020-03-05T10:04:31+0800
		 * @param    {[type]}                 id [description]
		 * @return   {[type]}                    [description]
		 */
		pathURL(id) {
			let host = sessionStorage.getItem('host')
			let redirectParams = sessionStorage.getItem('redirect_params')
			let link = `${this.BASE_URL}${redirectParams}&host=${host}&routerUrl=/home/resourceDetail&id=${id}`
			window.open(link)
		},
		//资源列表
		getResourceLs() {
			let success = (res => {
				this.subjectList = this.$g.subjectList
				let data = res.data;
				this.resourceList = data.data;
				this.total_number = data.data_sum;
				this.page_index = parseInt(data.page_index)
			});
			this.$ajax({
				url: '/api/resource/resource',
				method: 'get',
				params: {
					create_id: this.$g.user_id,
					page: this.page_index,
					size: this.page_size,
					name: this.resourceName,
					subject_id: this.subjectId,
					data_type: 2,
					not_in_file_type: 2,
					status: "1,2,3"
				},
				func: { success: success }
			})
		},
		//学科
		changeSelect(val) {
			this.page_index = 1
			this.getResourceLs();
		},
		//分页
		change_page(val) {
			this.page_index = val;
			this.getResourceLs();
		},
		//搜索资源
		changeInputName() {
			this.page_index = 1;
			this.getResourceLs()
		},
		//删除列表
		removeList(id) {
			this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				customClass: 'confirm-them'
			}).then(() => {
				let success = (res => {
					this.$message.success(res.msg);
					this.page_index = 1;
					this.getResourceLs()
				});
				this.$ajax({
					url: 'api/resource/resource',
					method: 'delete',
					params: {
						userid: this.$g.user_id,
						del_type: 1,
						id: id
					},
					func: { success: success }
				})
			}).catch(() => {});
		},
		/**
		 * /是否公开 
		 * @DateTime 2020-03-05T10:16:52+0800
		 * @param    {[type]}                 id   [id]
		 * @param    {[type]}                 type [off=公开， no=不公开]
		 * @return   {[type]}                      [description]
		 */
		whetherOpen(id, type) {

			this.$confirm('此操作是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				customClass: 'confirm-them'
			}).then(() => {

				let success = (res => {
					this.$message.success(res.msg)
					this.page_index = 1
					this.getResourceLs()
				})

				let data = {
					id: id,
					user_id: this.$g.user_id,
				}

				if (type === 'no') {

					data.authority = 0
					data.status = 1
				} else {
					data.authority = 1
					data.status = 2

					if (this.$store.getters.userInfo.check_rolebaseid <= 3 || this.$store.getters.userInfo.check_rolebaseid == 6) {
						data.status = 1
					} else {
						data.status = 2
					}
				}

				this.$ajax.put('api/resource/resource', data, { func: { success: success } })

			}).catch(() => {});
		},
		//MB单位转换
		ByteSwitch(bytes, decimals) {
			bytes = parseInt(bytes);
			decimals = parseInt(decimals);
			if (decimals > 8) {
				decimals = 8;
			}
			if (isNaN(decimals)) {
				decimals = 2;
			}
			var sz = ['B', 'K', 'M', 'G', 'T', 'P'];
			var factor = Math.floor(((bytes + '').length - 1) / 3);
			var result = bytes / Math.pow(1024, factor) + '';
			var index = result.indexOf('.');
			if (index == -1) {
				index = result.length - decimals - 1;
			}
			result = result.substr(0, index + decimals + 1);
			return result + sz[factor];

			var bytes = parseInt(val);

			if (bytes === 0) { return '0 B' };
			var k = 1024;
			var sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
			var i = Math.floor(Math.log(bytes) / Math.log(k))
			//return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
			var sum = (bytes / Math.pow(k, i)).toPrecision(3)
			// console.info(sum)
			return sum + ' ' + sizes[i];
			//toPrecision(3) 后面保留两位小数，如1.00GB
		},
		/**
		 * 资源统计饼图
		 * @DateTime 2020-03-05T10:27:05+0800
		 * @return   {[type]}                 [description]
		 */
		getchart() {
			let success = (res => {
				let data = res.data;

				let total = (1024 * 1024 * 1024) * 5, //总容量
					proportion = 0, //比例
					number = 0, //使用总数
					bytes = 0 //使用总数

				this.polar.legend.data = data; //文件类型
				this.polar.series[0].data = data; //文件类型数据

				this.polar.series[0].data.forEach((item) => { //获取文件使用的大小

					item.value = item.file_size
					// console.info( item.value, item.file_size)
					number += item.file_size ? parseInt(item.file_size) : 0
				});
				if (number <= 0) {
					this.$message.error('没发现相关的内容哦');
					return
				}

				//获取文件字节转换对应的大小单位
				bytes = this.ByteSwitch(number)
				var total_ = this.ByteSwitch(total)
				proportion = (parseInt(number) / parseInt(total) * 100).toPrecision(3);
				this.polar.title.text = `总容量 ${total_}，已使用 ${bytes}，比例 ${proportion}%`;
				//统计表的文件类型所占的比例
				this.polar.legend.formatter = function(param) {
					var sum = 0;
					var value = 0;
					for (var i = 0; i < data.length; i += 1) {
						sum += parseInt(data[i].value);
						if (param == data[i].name) {

							value = data[i].file_size ? parseInt(data[i].file_size) : 0;
						}
					}
					let sx = value / total * 100
					if (sx === 100) {
						return param + sx.toFixed(0) + '%';
					} else {
						return param + sx.toFixed(3) + '%';
					}
				}
				this.polar.series[0].itemStyle.normal.label.formatter = function(param) {
					var sum = 0;
					var value = 0;
					for (var i = 0; i < data.length; i += 1) {
						sum += parseInt(data[i].value);
						if (param.name == data[i].name) {

							value = data[i].file_size ? parseInt(data[i].file_size) : 0;
						}
					}
					let sx = value / total * 100
					if (sx === 100) {
						return param.name + sx.toFixed(0) + '%';
					} else {
						return param.name + sx.toFixed(3) + '%';
					}
				}
				this.isActive = true;
			});

			this.$ajax({
				url: '/api/resource/get_resource_percent',
				method: 'get',
				params: {
					userid: this.$g.user_id,
				},
				func: { success: success }
			})
		},

	},
}
</script>